package cn.edu.lingnan.servlet.score;

import cn.edu.lingnan.pojo.ScoreDTO;
import cn.edu.lingnan.service.ScoreService;
import cn.edu.lingnan.service.ScoreServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/scorepagequery", "/scorequerybycid"})
public class ScoreServlet extends HttpServlet {
    private ScoreService service=new ScoreServiceImp();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();

        switch (action) {
            case "/scorepagequery":
                listScoresByPage(request, response);
                break;
            case "/scorequerybycid":
                searchScoresByCid(request, response);
                break;
        }
    }

    private void listScoresByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 10;

        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        List<ScoreDTO> scores = service.ScorePageQuery(page, pageSize);
        int totalScores = service.getTotalScores();
        int totalPage = (int) Math.ceil(totalScores / (double) pageSize);

        request.setAttribute("scores", scores);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("pageSize", pageSize);

        request.getRequestDispatcher("/manager_score.jsp").forward(request, response);
    }

    private void searchScoresByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String cidParam = request.getParameter("cid");
        if (cidParam != null && !cidParam.isEmpty()) {
            int cid = Integer.parseInt(cidParam);
            List<ScoreDTO> scores = service.getScoresByCid(cid);

            request.setAttribute("scores", scores);
        } else {
            request.setAttribute("scores", new ArrayList<>()); // 没有查询到结果时设置空列表
        }
        request.setAttribute("currentPage", 1);
        request.setAttribute("totalPage", 1);
        request.setAttribute("pageSize", 10);

        request.getRequestDispatcher("/manager_score.jsp").forward(request, response);
    }
}